package com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.gatewayImpl.http;

import com.iwhalecloud.citybrain.flow.platform.manager.application.utils.ModelUtils;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.gateway.http.EventCallGateway;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.FlowModelVariableVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.ProcessModelVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowModelVariableRepository;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.ManagementService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * http工具类
 *
 * @author songxf
 * @date 2021/08/05
 */
@Slf4j
@Component
public class EventCallGatewayImpl implements EventCallGateway, Serializable {
    private static final long serialVersionUID = 740909463971550462L;

    @Lazy
    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private ManagementService managementService;

    @Autowired
    private FlowModelVariableRepository flowModelVariableRepository;

    @Lazy
    @Autowired
    private RuntimeService runtimeService;

    /**
     * 根据流程定义id查询部署id
     * @param processDefinitionId 流程定义id
     * @return 查询部署id
     */
    public String resolveDeploymentId(String processDefinitionId) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().
                processDefinitionId(processDefinitionId).singleResult();
        return processDefinition.getDeploymentId();
    }

    /**
     * 根据processDefinitionId获取modelId
     * @param processDefinitionId
     * @return 模型Id
     */
    public String resolveModelId(String processDefinitionId) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionId(processDefinitionId).singleResult();
        InputStream inputStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), processDefinition.getResourceName() + ".json");
        ProcessModelVo processModel = ModelUtils.getInstance().streamToModel(inputStream);
        return processModel.getModelId();
    }

    /**
     * 流程变量 插入全局变量 act_ru_variable
     * @param executionId
     * @param variableList
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveActModelVariable(String executionId, List<Map<String, String>> variableList) {
        Map<String, Object> v = new HashMap<>(variableList.size());
        for (Map<String, String> entry : variableList) {
            v.put(entry.get("code"), entry.get("value"));
        }
        runtimeService.setVariables(executionId, v);
    }

    /**
     * 获取手动添加的流程变量 act_ru_variable
     * @param executionId
     * @return
     */
    public Map<String, Object> getActModelVariables(String executionId) {
        return runtimeService.getVariables(executionId);
    }


    /**
     * 流程变量 插入数据库 flow_model_variable
     * @param processDefinitionId
     * @param variableList
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveFlowModelVariable(String processDefinitionId, String executionId, List<Map<String, String>> variableList) {
        String deploymentId = resolveDeploymentId(processDefinitionId);
        String modelId = resolveModelId(processDefinitionId);
        for (Map<String, String> entry : variableList) {
            FlowModelVariableVo variableEntity = new FlowModelVariableVo();
            variableEntity.setModelId(modelId);
            variableEntity.setDeployId(deploymentId);
            variableEntity.setName(entry.get("name"));
            variableEntity.setCode(entry.get("code"));
            variableEntity.setType(entry.get("type"));
            variableEntity.setDefaultValue(entry.get("value"));
            variableEntity.setDescription(entry.get("description"));
            flowModelVariableRepository.insertModelVariable(variableEntity);
        }
    }

    /**
     * 获取手动添加的流程变量 flow_model_variable
     * @param deploymentId
     * @return
     */
    public List<FlowModelVariableVo> getFlowModelVariables(String deploymentId) {
        return flowModelVariableRepository.getModelVariables(deploymentId);
    }

}
